package com.ai.bitcoin.controller;

import com.ai.bitcoin.bo.*;
import com.ai.bitcoin.common.resp.ResponseEntity;
import com.ai.bitcoin.constant.CodeConstant;
import com.ai.bitcoin.exception.BusinessException;
import com.ai.bitcoin.jpa.dao.BccUserDao;
import com.ai.bitcoin.jpa.entity.BccBasicInfo;
import com.ai.bitcoin.jpa.entity.BccPriceInfo;
import com.ai.bitcoin.jpa.entity.BccUser;
import com.ai.bitcoin.jpa.service.BccPriceInfoService;
import com.ai.bitcoin.service.MemberCenterService;
import com.ai.bitcoin.service.UserService;
import com.ai.bitcoin.service.WeiXinService;
import com.ai.bitcoin.vo.BccInfoVo;
import com.ai.bitcoin.vo.MemberCenterIndexAccounVO;
import com.ai.bitcoin.vo.MemberCenterIndexVO;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;

/**
 * @description: ${description}
 * @author: gulj
 * @create: 2018-07-07 16:55
 **/
@RestController
@RequestMapping("/member/center")
@Slf4j
public class MemberCenterController {
    @Autowired
    private MemberCenterService memberCenterService;
    @Autowired
    private WeiXinService weiXinService;
    @Autowired
    private UserService userService;
    @Autowired
    private BccPriceInfoService priceInfoService;
    @Autowired
    private BccUserDao bccUserDao;
    @Value("${asyncTimeout}")
    long asyncTimeout;

    @PostMapping("/index")
    public ResponseEntity index(@RequestBody @Valid MemberCenterIndexBO memberCenterIndexBO) {
        long startTime = System.currentTimeMillis();
        log.info("【MemberCenterController#index】参数：{}", memberCenterIndexBO);
        MemberCenterIndexVO memberCenterIndexVO = memberCenterService.index(memberCenterIndexBO);
        long endTime = System.currentTimeMillis();
        long spendSeconds = (endTime - startTime) / 1000;
        log.info("【MemberCenterController#index 耗时 {} 秒】", spendSeconds);
        return new ResponseEntity(200, "success", memberCenterIndexVO);
    }

    @PostMapping("/bitcoins")
    public ResponseEntity bitcoins(@RequestBody @Valid MemberCenterBitcoinsBO bitcoinsBO) {
        long startTime = System.currentTimeMillis();
        log.info("【MemberCenterController#bitcoins】参数：{}", bitcoinsBO);
        List<BccBasicInfo> basicInfoList = memberCenterService.bitcoins(bitcoinsBO);
        List<BccInfoVo> bccInfoVoList = Lists.newArrayList();
        for (BccBasicInfo bcc : basicInfoList) {
            BccInfoVo vo = new BccInfoVo();
            BeanUtils.copyProperties(bcc, vo);
            BccPriceInfo priceInfo = priceInfoService.getDao().findTop1ByBccIdOrderByPriceTimestampDesc(bcc.getBccId());
            if (priceInfo != null) {
                vo.setChange1d(priceInfo.getChange1d());
                //暂时不进行四舍五入
                if (NumberUtils.isCreatable(priceInfo.getPriceCny())) {
                    vo.setPriceCny(new DecimalFormat("0.0000").format(Double.valueOf(priceInfo.getPriceCny())));
                }
            }
            bccInfoVoList.add(vo);
        }
        long endTime = System.currentTimeMillis();
        long spendSeconds = (endTime - startTime) / 1000;
        log.info("【MemberCenterController#bitcoins 耗时 {} 秒】", spendSeconds);
        return new ResponseEntity(200, "success", bccInfoVoList);
    }

    @PostMapping("/updateStatus")
    public ResponseEntity updateStatus(@RequestBody @Valid MemberCenterUpateStatusBO upateStatusBO) {
        memberCenterService.updateStatus(upateStatusBO);
        return new ResponseEntity(200, "success", null);
    }

    /**
     * 取得用户信息
     *
     * @param userBO
     * @return
     * @throws BusinessException
     */
    @PostMapping(value = "/getUserInfo", produces = "application/json;charset=UTF-8")
    public ResponseEntity getUserInfo(@RequestBody @Valid MemberCenterUpdateUserBO userBO) throws BusinessException {
        if (StringUtils.isEmpty(userBO.getOpenId())) {
            throw new BusinessException(CodeConstant.BUSINESS_ERROR, "非法请求。");
        }
        long startTime = System.currentTimeMillis();
        log.info("【MemberCenterController#getUserInfo】参数：{}", userBO);
        BccUser user = bccUserDao.findByOpenId(userBO.getOpenId());
        log.info("【MemberCenterController#getUserInfo 耗时 {} 秒】", (System.currentTimeMillis() - startTime) / 1000);
        return new ResponseEntity(200, "success", user);
    }

    /**
     * 更新用户信息
     *
     * @param request
     * @param userBO
     * @return
     * @throws BusinessException
     */
    @PostMapping(value = "/updateUserInfo", produces = "application/json;charset=UTF-8")
    public ResponseEntity updateUserInfo(final HttpServletRequest request, @RequestBody @Valid MemberCenterUpdateUserBO userBO) throws BusinessException {
        long startTime = System.currentTimeMillis();
        log.info("【MemberCenterController#updateUserInfo】参数：{}", userBO);
        userService.updateUserInfo(userBO);
        log.info("【MemberCenterController#updateUserInfo 耗时 {} 秒】", (System.currentTimeMillis() - startTime) / 1000);
        return new ResponseEntity(200, "success", null);
    }

    /**
     * PLC记录
     *
     * @param plcAccountBO
     * @return
     */
    @PostMapping("/plcAccount")
    public ResponseEntity plcAccount(@RequestBody @Valid MemberCenterPlcAccountBO plcAccountBO) {
        MemberCenterIndexAccounVO indexAccounVO = memberCenterService.queryBccUserPLcRecord(plcAccountBO.getOpenId());
        return new ResponseEntity(200, "success", indexAccounVO);
    }

    //我的海报
    @GetMapping(value = "/poster/{openId}", produces = MediaType.IMAGE_JPEG_VALUE)
    public org.springframework.http.ResponseEntity poster(@PathVariable String openId) {

        try {
            File posterFile = memberCenterService.getPoster(openId);
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_JPEG_VALUE);
            return new org.springframework.http.ResponseEntity<>(FileUtils.readFileToByteArray(posterFile), headers, HttpStatus.OK);
        } catch (IOException e) {
            log.warn(e.getMessage(), e);
            return new org.springframework.http.ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }
}
